<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/generalFunctions.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/controller/ctlAbstract.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busQuestion.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busProvider.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busAddress.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busCategory.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busResource.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busItem.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busAvatar.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busOccupation.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busFriend.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busLocation.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/user.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/question.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/provider.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/address.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/category.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/resource.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/item.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/friend.php';

/**
 * This is the class handle the view function for the page
 */
class ViewController extends AbstractController {
	private $_userBus;
	private $_questionBus;
	private $_providerBus;
	private $_addressBus;
	private $_categoryBus;
	private $_resourceBus;
	private $_itemBus;
	private $_avatarBus;
	private $_occupationBus;
	private $_friendBus;
	private $_locationBus;
	
	private function getViewDataForProviders($providers, &$ids, &$arrRes, &$imgs, &$arrText, &$arrLink) {
		global $ubi;
		
		$imgs = array();
		if (isset($providers)) {
			foreach ($providers as $provider) {
				$ids[] = $provider->getProviderID();
				$arrResID = explode(' ', trim($provider->getResourceList()));
				$imgs[$provider->getProviderID()] = $ubi['SERVER']['RESOURCE_PATH'] . '/' .
				$this->_resourceBus->getImgOfResource($arrResID[0]);
				$arrText[$provider->getProviderID()] = $provider->getProvider();
				$arrLink[$provider->getProviderID()] = 'index.php?view&type=provider&id=' . $provider->getProviderID();
			}
		}
	}
	
	private function getViewDataForItems($items, &$ids, &$arrRes, &$imgs, &$arrText, &$arrLink ) {
		global $ubi;
		
		$imgs = array();
		if (isset($items)) {
			foreach ($items as $item) {
				$ids[] = $item->getItemID();
				$arrResID = explode(' ', trim($item->getResourceList()));
				$imgs[$item->getItemID()] = $ubi['SERVER']['RESOURCE_PATH'] . '/' .
				$this->_resourceBus->getImgOfResource($arrResID[0]);
				$arrText[$item->getItemID()] = $item->getItem();
				$arrLink[$item->getItemID()] = 'index.php?view&type=item&id=' . $item->getItemID();
			}
		}
	}
	
	//begin class ViewController
	public function main(array $getVars) {
		global $ubi;
		
		$this->_questionBus = new QuestionBus();
		$this->_userBus = new UserBus();
		$this->_providerBus = new ProviderBus();
		$this->_addressBus = new AddressBus();
		$this->_categoryBus = new CategoryBus();
		$this->_resourceBus = new ResourceBus();
		$this->_itemBus = new ItemBus();
		$this->_avatarBus = new AvatarBus();
		$this->_occupationBus = new OccupationBus();
		$this->_friendBus = new FriendBus();
		$this->_locationBus = new LocationBus();
		
		//begin function main		
		//view user
		if (strtolower($getVars['type']) == 'user') {
			if (isset($getVars['username'])) {
				$user = $this->_userBus->getUserByUserName($getVars['username']);
				if (isset($user)) {
					$getVars['userid'] = $user->getUserID();
				} else {
					return;
				}
			}
			
			//begin if view user
			$isMine = 0;
			$userString;
			if (isset($getVars['username']) && $getVars['username'] == 'me') {
				$userString = $_SESSION['username'];
			} else {
				$userString = isset($getVars['username'])?$getVars['username']:$getVars['userid'];
			}
			
			//if retrieve successfully
			if ($this->_userBus->isExistedByUserName($userString) || $this->_userBus->isExistedByUserId($userString)) {
				$getVars['page'] = 'viewUser';
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewUser.php';				
			} else {
				$notice = 'UserNotExist';
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewNotice.php';
			}			
		} else if ($getVars['type'] == 'provider') {
			if (isset($getVars['id'])) {
				$id = $getVars['id'];
				$this->_providerBus->incFrequency($id);
				$providerModel = $this->_providerBus->getProvider($id);
				$address = $this->_addressBus->getAddress($providerModel->getAddressID());
				$user = $this->_userBus->getUser($providerModel->getUserID());
				$img = $this->_avatarBus->getResource($user->getUserID())->getResourceName();	

				if ($providerModel->getMapResourceID() != null) {
					$mapRes = $this->_resourceBus->getResource($providerModel->getMapResourceID());
					$imgUrl = $ubi['SERVER']['RESOURCE_PATH'] . '/' . $mapRes->getResourceName();
				} else {
					$imgUrl = $ubi['SERVER']['RESOURCE_PATH'] . '/' . $this->_providerBus->updateMapImage($id);
				}
				
				$uid = isset($_SESSION['userid'])?$_SESSION['userid']:null;
				if ($uid) {
					$isFav = $this->_providerBus->isFavourite($id, $uid);
					$isMin =  $this->_providerBus->isMinus($id, $uid);
					$isPlus = $this->_providerBus->isPlus($id, $uid);
				}
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewProvider.php';
			}
		} else if ($getVars['type'] == 'item') {
			if (isset($getVars['id'])) {
				$id = $getVars['id'];
				$this->_itemBus->incFrequency($id);
				$itemModel = $this->_itemBus->getItem($id);
				
				$user = $this->_userBus->getUser($itemModel->getUserID());
				$img = $this->_avatarBus->getResource($user->getUserID())->getResourceName();
				
				$uid = $_SESSION['userid'];
				if ($uid) {
					$isFav = $this->_itemBus->isFavourite($id, $uid);
					$isMin =  $this->_itemBus->isMinus($id, $uid);
					$isPlus = $this->_itemBus->isPlus($id, $uid);
				}
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewItem.php';
			}
		} else if ($getVars['type'] == 'listItem') {
			if (isset($getVars['id'])) {
				$listItem = $this->_itemBus->getItemsByUserId($getVars['id']);
				$imgs = $this->_itemBus->getListImgs($listItem);
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewListItem.php';
			}
		} else if ($getVars['type'] == 'listProvider') {
			if (isset($getVars['id'])) {
				$listProvider = $this->_providerBus->getProvidersByUserId($getVars['id']);								
				$imgs = $this->_providerBus->getListImgs($listProvider);
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewListProvider.php';
			}
		} else if ($getVars['type'] == 'shareProvider') {
			$arrCatProvider1 = $this->_categoryBus->getCategoryProviderList(0);
			$catProvider1 = $arrCatProvider1[0];										
			$arrCatProvider2 = $this->_categoryBus->getCategoryProviderList($catProvider1->getCategoryID());
			
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewShareProvider.php';
		} else if ($getVars['type'] == 'shareItem') {
			$arrCatItem1 = $this->_categoryBus->getCategoryItemList(0);
			$catItem1 = $arrCatItem1[0];							
			$arrCatItem2 = $this->_categoryBus->getCategoryItemList($catItem1->getCategoryID());
			
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewShareItem.php';
		} else if ($getVars['type'] == 'sharePost') {
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewSharePost.php';
		} else if ($getVars['type'] == 'providers') {
			$arrCities = $this->_locationBus->getLocationList(NULL);
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewProviders.php';
		} else if ($getVars['type'] == 'items') {
			$arrCities = $this->_locationBus->getLocationList(NULL);
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewItems.php';
		} else if ($getVars['type'] == 'posts') {
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewPosts.php';
		} else if ($getVars['type'] == 'listProviders') {
			$page = 1;
			if (array_key_exists('page', $getVars)) {
				$page = $getVars['page'];
			}
			$providers = $this->_providerBus->searchAdvancedProviders($_POST['region'], NULL, NULL, NULL, NULL, NULL, $page - 1);
			$this->getViewDataForProviders($providers, $ids, $arrRes, $imgs, $arrText, $arrLink);
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewListObjects.php';
		} else if ($getVars['type'] == 'listItems') {
			$items = $this->_itemBus->searchItemsByRegion($_POST['region']);
			$this->getViewDataForItems($items, $ids, $arrRes, $imgs, $arrText, $arrLink);
				
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewListObjects.php';
		} else if ($getVars['type'] == 'search') {
			$imgs = array();
			$arrText = array();
			$arrLink = array();
			$ids = array();
			$searchText = $_POST['searchText'];
			if ($_POST['searchCriteria'] == 'item') {
				$items = $this->_itemBus->searchItems($searchText);
				if ($items) {
					foreach ($items as $item) {
						$ids[] = $item->getItemID();
						$arrResID = explode(' ', trim($item->getResourceList()));
						$imgs[$item->getItemID()] = $ubi['SERVER']['RESOURCE_PATH'] . '/' . 
							$this->_resourceBus->getImgOfResource($arrResID[0]);
						$arrText[$item->getItemID()] = $item->getItem();
						$arrLink[$item->getItemID()] = 'index.php?view&type=item&id=' . $item->getItemID(); 
					}
				}	
			} else {
				$providers = $this->_providerBus->searchProviders($searchText);
				if ($providers) {
					foreach ($providers as $provider) {
						$ids[] = $provider->getProviderID();
						$arrResID = explode(' ', trim($provider->getResourceList()));
						$imgs[$provider->getProviderID()] = $ubi['SERVER']['RESOURCE_PATH'] . '/' .
							$this->_resourceBus->getImgOfResource($arrResID[0]);
						$arrText[$provider->getProviderID()] = $provider->getProvider();
						$arrLink[$provider->getProviderID()] = 'index.php?view&type=provider&id=' . $provider->getProviderID(); 
					}
				}
			}
			
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewSearchResults.php';
		} else if ($getVars['type'] == 'score') {
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewCalcScore.php';
		} else if ($getVars['type'] == 'avatar') {
			$userid = $getVars['userid'];
			$avatars = $this->_avatarBus->getAvatars($userid);
			if ($avatars) {
				$resources = array();
				foreach ($avatars as $avatar) {
					$resources[$avatar->getResourceID()] = $this->_resourceBus->getResource($avatar->getResourceID());
				}
			}
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewUserAvatars.php';;
		} else if ($getVars['type'] == 'profile') {
			$userID = $_SESSION['userid'];
			if ($userID) {
				$user = $this->_userBus->getUser($userID);
				$address = $this->_addressBus->getAddress($user->getAddressID());
				$occupationList = $this->_occupationBus->getOccupationList();

				$isCommentOnMyPost = "unchecked";
				$isWriteOnMyWall = "unchecked";
				$isPlusOnMyComment = "unchecked";
				$isMinusOnMyComment = "unchecked";
				$isPlusOnMyPost = "unchecked";
				$isMinusOnMyPost = "unchecked";
				$isFavOnMyPost = "unchecked";
				$isUnFavOnMyPost = "unchecked";
				
				if (!in_array($ubi['EMAIL']['COMMENT_ON_MY_POST'], $user->getEmailPrivacies())) {
					$isCommentOnMyPost = "checked";
				}
				if (!in_array($ubi['EMAIL']['WRITE_ON_MY_WALL'], $user->getEmailPrivacies())) {
					$isWriteOnMyWall = "checked";
				}
				if (!in_array($ubi['EMAIL']['PLUS_MY_COMMENT'], $user->getEmailPrivacies())) {
					$isPlusOnMyComment = "checked";
				}
				if (!in_array($ubi['EMAIL']['MINUS_MY_COMMENT'], $user->getEmailPrivacies())) {
					$isMinusOnMyComment = "checked";
				}
				if (!in_array($ubi['EMAIL']['PLUS_MY_POST'], $user->getEmailPrivacies())) {
					$isPlusOnMyPost = "checked";
				}
				if (!in_array($ubi['EMAIL']['MINUS_MY_POST'], $user->getEmailPrivacies())) {
					$isMinusOnMyPost = "checked";
				}
				if (!in_array($ubi['EMAIL']['FAVOURITE_MY_POST'], $user->getEmailPrivacies())) {
					$isFavOnMyPost = "checked";
				}
				if (!in_array($ubi['EMAIL']['UNFAVOURITE_MY_POST'], $user->getEmailPrivacies())) {
					$isUnFavOnMyPost = "checked";
				}
			}
			
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewUserUpdateInformation.php';
		} else if ($getVars['type'] == 'member') {
			$numberOfPages = GeneralFunctions::calculateNumberOfPages($this->_userBus->getNumberOfUser(), $ubi['SITE']['N_USER_PER_PAGE']);
			
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewAllMembers.php';
		} else if ($getVars['type'] == 'listMembers') {
			if (!isset($getVars['page'])) {
				$getVars['page'] = 1;
			}		
			$numberOfUsers = $this->_userBus->getNumberOfUser();
			$numberOfPages = GeneralFunctions::calculateNumberOfPages($numberOfUsers, $ubi['SITE']['N_USER_PER_PAGE']);
			if ($getVars['page'] == 'last') {
				$getVars['page'] = $numberOfPages;
			}											
			$users = $this->_userBus->getUsersOfPage($getVars['page']);
			$imgs = $this->_avatarBus->getAvatarPathOfUsers($users);			
			
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewListMembers.php';
		} else if ($getVars['type'] == 'friend') {
			
			$numberOfPages = GeneralFunctions::calculateNumberOfPages($this->_userBus->getNumberOfUser(), $ubi['SITE']['N_USER_PER_PAGE']);
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewAllFriends.php';
		} else if ($getVars['type'] == 'listMembers') {
			if (!isset($getVars['page'])) {
				$getVars['page'] = 1;
			}		
			$numberOfUsers = $this->_userBus->getNumberOfUser();
			$numberOfPages = GeneralFunctions::calculateNumberOfPages($numberOfUsers, $ubi['SITE']['N_USER_PER_PAGE']);
			if ($getVars['page'] == 'last') {
				$getVars['page'] = $numberOfPages;
			}											
			$users = $this->_userBus->getUsersOfPage($getVars['page']);
			$imgs = $this->_avatarBus->getAvatarPathOfUsers($users);			
			
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewListMembers.php';
		} else if ($getVars['type'] == 'listFriends') {
			$userID = $_SESSION['userid'];
			if ($userID) {
				if (!isset($getVars['page'])) {
					$getVars['page'] = 1;
				}		
				$numberOfFriends = $this->_friendBus->getNumberOfFriend($userID);
				$numberOfPages = GeneralFunctions::calculateNumberOfPages($numberOfFriends, $ubi['SITE']['N_USER_PER_PAGE']);
				if ($getVars['page'] == 'last') {
					$getVars['page'] = $numberOfPages;
				}											
				$friends = $this->_friendBus->getFriendsByUserIdOfPage($userID, $getVars['page']);
				$imgs = $this->_avatarBus->getAvatarPathOfUsers($friends);			
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewListFriends.php';
			}
		} else if ($getVars['type'] == 'advancedSearch') {
			if (array_key_exists('cat', $getVars) && $getVars['cat'] == 'provider') {
				$city = '';
				if (isset($_POST['selCity'])) {
					$city = $_POST['selCity'];
				}
				
				$district = '';
				if (isset($_POST['selDistrict'])) {
					$district = $_POST['selDistrict'];
				}
				
				$ward = '';
				if (isset($_POST['selWard'])) {
					$ward = $_POST['selWard'];
				}
				
				$number = '';
				if (isset($_POST['txtNumber'])) {
					$number = $_POST['txtNumber'];
				}
				
				$street = '';
				if (isset($_POST['txtStreet'])) {
					$street = $_POST['txtStreet'];
				}
				
				$providerName = '';
				if (isset($_POST['txtProvider'])) {
					$providerName = $_POST['txtProvider'];
				}
								
				$providers = $this->_providerBus->searchAdvancedProviders($city, $district, $ward, $number, $street, $providerName);
				$imgs = array();
				if (isset($providers)) {
					foreach ($providers as $provider) {
						$ids[] = $provider->getProviderID();
						$arrResID = explode(' ', trim($provider->getResourceList()));
						$imgs[$provider->getProviderID()] = $ubi['SERVER']['RESOURCE_PATH'] . '/' .
						$this->_resourceBus->getImgOfResource($arrResID[0]);
						$arrText[$provider->getProviderID()] = $provider->getProvider();
						$arrLink[$provider->getProviderID()] = 'index.php?view&type=provider&id=' . $provider->getProviderID();
					}
				}
			} else if (array_key_exists('cat', $getVars) && $getVars['cat'] == 'item') {
				$itemName = '';
				if (isset($_POST['txtItemName'])) {
					$itemName = $_POST['txtItemName'];
				}	
				
				$beginPrice = '';
				if (isset($_POST['txtBeginPrice'])) {
					$beginPrice = $_POST['txtBeginPrice'];
				}
				
				$endPrice = '';
				if (isset($_POST['txtEndPrice'])) {
					$endPrice = $_POST['txtEndPrice'];
				}
				
				$unit = '';
				if (isset($_POST['txtUnit'])) {
					$unit = $_POST['txtUnit'];
				}
				
				$items = $this->_itemBus->searchAdvancedItems($itemName, $beginPrice, $endPrice, $unit);
				$imgs = array();
				if (isset($items)) {
					foreach ($items as $item) {
						$ids[] = $item->getItemID();
						$arrResID = explode(' ', trim($item->getResourceList()));
						$imgs[$item->getItemID()] = $ubi['SERVER']['RESOURCE_PATH'] . '/' .
						$this->_resourceBus->getImgOfResource($arrResID[0]);
						$arrText[$item->getItemID()] = $item->getItem();
						$arrLink[$item->getItemID()] = 'index.php?view&type=item&id=' . $item->getItemID();
					}
				}
			}
			
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewAdvancedSearch.php';
		}	
	}//end function main
}//end class ViewController
?>